# -*- coding: utf-8 -*-

'''eof
name:当月订烟额
code:MG_Smoke_Money
tableName:
columnName:
groups:烟商经营情况
dependencies:YSDDH_BTM
type:常用指标
datasourceType:在线指标
description:
eof'''


import sys
import pandas as pd
from datetime import datetime
import json
from dateutil.relativedelta import relativedelta

reload(sys)
sys.setdefaultencoding('utf-8')


def format_data():
    try:
        indent = json.loads(YSDDH_BTM[0]['data'])["data"]["indent"]
        return indent if isinstance(indent, list) and len(indent) > 0 else [{}]
    except:
        return [{}]


def get_date_list(month):
    try:
        now = datetime.now()
        month_time = now + relativedelta(days=-month)
        aaa = [(month_time + pd.tseries.offsets.DateOffset(days=i)).strftime('%Y%m%d') for i in [-30, 0]]
        return aaa
    except:
        return None


def float_check(num):
    try:
        float(num)
        return True
    except:
        return False


# 统一转成datetime对象，只能转年月日的字符串
def date_format(time):
    import re
    r = re.compile(r'\D+')
    try:
        date = datetime.strptime(time, '%Y.%m.%d')
    except:
        try:
            date = datetime.strptime(time, '%Y-%m-%d')
        except:
            try:
                date = datetime.strptime(time, '%Y/%m/%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.strptime(tmp, '%Y%m%d')
                except:
                    date = None
    return date


def MG_Smoke_Money():
    null_type_list = ['', None, 'null', 'Null', 'NULL', '/', ' ']
    try:
        indent_list = format_data()
        date_list = get_date_list(0)
        if indent_list == [{}]:
            return u'缺失值'
        else:
            if len(indent_list) >= 1:
                total = []
                for i in indent_list:
                    if i.get("indentDate") not in null_type_list and date_format(
                            i.get("indentDate")) not in null_type_list and float_check(i.get("indentMoney")):
                        indent_date = datetime.strftime(date_format(i.get("indentDate")), '%Y%m%d')
                        if date_list[0] < indent_date <= date_list[1]:
                            total.append(float(i.get("indentMoney")))
                return sum(total)
            else:
                return u'缺失值'
    except:
        return u'缺失值'


result = MG_Smoke_Money()